package com.example.first.thread;

import java.time.LocalDateTime;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author LSQ
 * @Description 练习 synchronized 加 runnable
 * @date 2021/11/5 21:43
 * @Version 1.0
 */

public class Worker2 implements Runnable {

    private People people;
    private CountDownLatch countDownLatch;
    private ReentrantLock reentrantLock;

    public Worker2(People people, CountDownLatch countDownLatch) {
        this.people = people;
        this.countDownLatch = countDownLatch;
    }

    public Worker2(People people, CountDownLatch countDownLatch, ReentrantLock reentrantLock) {
        this.people = people;
        this.countDownLatch = countDownLatch;
        this.reentrantLock = reentrantLock;
    }

    public void doService1() {
        System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " start doService1");
        people.getUp();
    }

    public void doService2() {
        System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " start doService2");
        people.getFood();
    }

    public void doService3() {
        System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " start doService3");
        people.eat();
    }

    @Override
    public void run() {
        System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " prepare running..");

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 可以同时起床
        doService1();

        try {
            reentrantLock.lock();
            System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " get lock!! before start get food!");
            // 只有一个人抢到饭碗打饭
            doService2();
        } finally {
            System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " unlock! after end get food!");
            reentrantLock.unlock();
        }

        // 模拟移动了10步 到自己的位置吃饭
        for (int i = 0; i < 10; i++) {
            System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " " + people.getName() + " after get food, moving step " + i);

            try {
                TimeUnit.MILLISECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 吃饭，可以同时吃
        doService3();

        System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " end running..");
        countDownLatch.countDown();
    }

}
